import flask
import json


# print(__name__) #__main__,代表当前Python文件
from config.db import query_db, change_db

server = flask.Flask(__name__) #起动一个服务,把咱们当前这个Python文件，当做一个服务

#装饰器
#ip:8000/index?uge
@server.route('/index',methods=['get']) #默认是get请求，可以不写或是同时写get,post
def index():
    res = {'msg':'这是我开发的第一个接口', 'msg_code': 0}
    return json.dumps(res, ensure_ascii=False) #二进制转化为utf-8

@server.route('/reg', methods=['post'])
def reg():
    username = flask.request.values.get('username')
    pwd = flask.request.values.get('passwd')
    if username and pwd:
        sql = 'select * from flask.my_user where username="%s";' %username
        if change_db(sql):
            res = {'msg':'用户已存在', 'msg_code':2001}
        else:
            insert_sql = 'insert into flask.my_user (username,passwd)VALUES ("%s","%s");' %(username,pwd)
            change_db(insert_sql)
            res = {'msg':'注册成功.', 'msg_code':0}
    else:
        res = {'msg':'必填字段未填，请查看接口文档!', 'msg_code':1001}
        #1001必填字段未填
    return json.dumps(res, ensure_ascii=False)
@server.route('/quer', methods=['post'])
def quer():
    username = flask.request.values.get('username')
    sql = 'select * from flask.my_user where username="%s";' % username
    if change_db(sql):
        c=change_db(sql)
        d = []
        for i in c:
            name = i[1]
            pwd = i[2]
            c = {name: pwd}
            d.append(c)
        res = {'msg': '查询成功', 'msg_code': 2001, 'text':d}
    else:
        res = {'msg': '用户未查询到', 'msg_code': 2001}
    return json.dumps(res, ensure_ascii=False)
#debug=True，修改代码后，不需要重启服务，它会帮你自动重启
server.run(port=7777, debug=True, host='127.0.0.1')  #起动服务。默认端口号是5000,
# host='0.0.0.0'指定后，别人可以通过ip访问，监听所有的网卡